<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <template #slot-left>
          <span>共 {{ total }} 条记录</span>
        </template>
        <template #slot-right>
          <el-button
            v-power="'import'"
            type="danger"
            size="small"
            @click="$router.push('/excel')"
          >导入excel</el-button>
          <el-button
            v-power="'export'"
            type="success"
            size="small"
            @click="downloadExcel"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 员工列表 -->
      <el-card class="employess-list">
        <el-table
          :data="employeesList"
          style="width: 100%"
          border
          :default-sort="{ mobile: 'date', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template v-slot="scope">
              <!-- <img class="staffPhoto" :src="scope.row.staffPhoto"> -->
              <!-- 如果src有值，图片渲染成功，就显示图片，如果渲染失败，就显示插槽中默认的图片 -->
              <image-holder :src="scope.row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column
            prop="formOfEmployment"
            :formatter="formatter"
            label="聘用形式"
          />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="correctionTime" label="转正时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" width="280">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="setEmpFn(scope.row.id)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployeesFn(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          :current-page="query.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 新增弹框 -->
        <el-dialog
          title="新增员工"
          :visible.sync="showDialog"
          width="50%"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="closeDialog"
        >
          <emp-dialog
            ref="addEmpt"
            @closeDialogEvent="closeDialogFn"
            @updateListEvent="updateListFn"
          />
        </el-dialog>
        <!-- 分配角色弹框 -->
        <el-dialog title="分配角色" :visible.sync="showRoleDialog" width="50%">
          <assign-role v-if="showRoleDialog" :role-id="roleId" @closeDialog="showRoleDialog = false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入API
import { getEmployeesListAPI, delEmployeeAPI } from '@/api/employees'

// 导入枚举的数据-------聘用形式
import formOfEmployment from '@/constant/employees'
import empDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'
import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: { empDialog, AssignRole },
  // 过滤器进行时间格式化
  filters: {
    formatTime(value) {
      // console.log(value)
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1,
        size: 10
      },
      total: 0,
      employeesList: [],
      showDialog: false,
      showRoleDialog: false, // 控制分配角色弹框的显示与隐藏
      roleId: ''
    }
  },
  created() {
    this.getEmployeesListFn()
  },
  methods: {
    // 点击分配角色时触发
    setEmpFn(id) {
      this.showRoleDialog = true
      this.roleId = id
    },
    // 将后端返回的数据，转成excel需要的
    transData(rows) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      // 获取表头

      // 获取的所有的key
      const headerArr = Object.keys(rows[0])
      // 获取所有的中文值，形成表头
      const header = headerArr.map((key) => {
        return map[key]
      })

      // 获取具体数据
      const data = rows.map((item) => {
        return Object.values(item)
      })

      return { header, data }
    },
    // 导出excel
    async downloadExcel() {
      // 获取最新的数据
      const res = await getEmployeesListAPI(this.query)
      console.log(res)
      const excelData = this.transData(res.data.rows)
      console.log(excelData)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: excelData.header, // 表头 必填
          data: excelData.data, // 具体数据 必填
          filename: '员工列表', // 非必填 导出时的文件名
          autoWidth: true, // 非必填 自适应
          bookType: 'xlsx' // 非必填  导出的类型
        })
      })
    },
    // 弹框关闭时，触发
    closeDialog() {
      // 获取组件实例，调用resetForm方法
      this.$refs.addEmpt.resetForm()
    },
    // 点击确定 关闭弹框，重新渲染数据
    updateListFn() {
      this.showDialog = false
      this.getEmployeesListFn()
    },
    // 点击取消，关闭弹框
    closeDialogFn() {
      this.showDialog = false
    },
    // 删除员工
    async delEmployeesFn(id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该员工, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 点击取消 直接提示
      if (confirmRes === 'cancel') return this.$message('您已取消了删除')
      // 点击确定。调用接口
      const res = await delEmployeeAPI(id)
      // 如果删除的是最后一页的最后一条数据，就显示，前一页的数据
      if (this.employeesList.length === 1) {
        this.query.page--
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }
      // 给用户提示
      this.$message.success(res.message)
      // 刷新页面
      this.getEmployeesListFn()
    },
    // 格式化聘用形式
    // cellValue 表格中的数据
    formatter(row, column, cellValue, index) {
      // 使用 find 方法 找到枚举中聘用形式数据的 id 与 当前单元格内的数据进行对比
      // 找到后 赋值给 obj  最后将结果 返回 ：如果有对应的就返回对应的value，否则为 未知
      const obj = formOfEmployment.hireType.find(
        (item) => item.id === Number(cellValue)
      )
      return obj ? obj.value : '未知'
    },
    // 获取员工列表
    async getEmployeesListFn() {
      const res = await getEmployeesListAPI(this.query)
      // console.log(res)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },
    // 当前每页显示的条数
    handleSizeChange(newPageSize) {
      this.query.size = newPageSize
      this.getEmployeesListFn()
    },
    // 当前每页的页码
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeesListFn()
    }
  }
}
</script>

<style lang="scss" scoped>
.employess-list {
  margin-top: 10px;
}
.el-pagination {
  text-align: center;
  margin-top: 20px;
}
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
